layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * Dispatch Order Management
     */
    var TransportDispatch = {
        tableId: "transportDispatchTable"
    };

    /**
     * Initialize table columns
     */
    TransportDispatch.initColumn = function () {
        return [[
            {field: 'getUnit', sort: true, title: 'Receiving Unit', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'getLocation', sort: true, title: 'Receiving Address', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'customerOrder', sort: true, title: 'Customer Order No.', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'goodsName', sort: true, title: 'Product Name', style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: 'Total: '},
            {field: 'transportPutvolume', sort: true, title: 'Volume', totalRow: true, style:'font-weight: 600;'},
            {field: 'num', sort: true, title: 'Quantity', totalRow: true, style:'font-weight: 600;'},
            {field: 'tooDeployVolume', sort: true, title: 'Configured Volume', totalRow: true, style:'font-weight: 600;'},
            {field: 'tooDeployNum', sort: true, title: 'Configured Quantity', totalRow: true, style:'font-weight: 600;color: #2b85e4;text-decoration:underline;',edit:'text'},
            {align: 'center', toolbar: '#tableBar', title: 'Operation'}
        ]];
    };

    TransportDispatch.search = function () {
        var queryData = {};
        queryData['customerOrder'] = $("#customerOrder").val();
        queryData['goodsName'] = $("#goodsName").val();
        table.reload(TransportDispatch.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

	function GetUrlByParamName(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var URL =  decodeURI(window.location.search);
        var r = URL.substr(1).match(reg);
        if(r!=null){
            //decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码
            return  decodeURI(r[2]);
        };
        return null;
    };

    // Render table
    var tableResult = table.render({
        elem: '#' + TransportDispatch.tableId,
        url: Feng.ctxPath + '/orderTransportDispatch/listOrder?carnumbger='+GetUrlByParamName("carnumbger"),
        page: false,
        limit: 1000,
        height: "full-60",
        totalRow: true,
        toolbar: '#toolbarDemo', //Enable header toolbar and bind left template
        cellMinWidth: 100,
        cols: TransportDispatch.initColumn()
    });

    // Edit cell event
    table.on('edit(' + TransportDispatch.tableId + ')', function (obj) {
        var data = obj.data;//Get all key-value pairs in the row
		var value = obj.value;//Modified value
		if(value == ''){
			table.reload('transportDispatchTable')	
    		layer.msg('Please enter a valid number'); 
			return
		}
		if(typeof parseFloat(value) != 'number' ||  parseFloat(value) <= 0){
			table.reload('transportDispatchTable')	
    		layer.msg('Please enter a valid positive number'); 
			return
		}
		if(parseFloat(value) > parseFloat(data.num)){
			table.reload('transportDispatchTable')	
    		layer.msg('Exceeding order quantity'); 
			return
		}
		
        var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/editGoods?id="+data.id+"&tooDeployNum="+value, function (data) {
    		if (data.success) {
                Feng.success("Update successful!");
				parent.submit = 1
        		table.reload(TransportDispatch.tableId);
			} else {
                Feng.error("Update failed! " + data.message);
			}
        }, function (data) {
            Feng.error("Update failed! " + data.responseJSON.message + "!");
        });
        ajax.start();
    });

    // Search button click event
    $('#btnSearch').click(function () {
        TransportDispatch.search();
    });

    // Toolbar click event
    table.on('tool(' + TransportDispatch.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'delete') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/removeGoods?carnumbger="+data.carnumbger+"&transportNumber="+data.transportNumber+"&goodsId="+data.goodsId, function (data) {
            		if (data.success) {
	                    Feng.success("Delete successful!");
	                    parent.submit = 1
	            		table.reload(TransportDispatch.tableId);
					} else {
	                    Feng.error("Delete failed! " + data.message);
					}
                }, function (data) {
                    Feng.error("Delete failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Are you sure to delete this product?", operation);
        }
    });
});
